package com.axend.aerosense.room.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.ViewModelProvider;

import com.axend.aerosense.base.livedatabus.LiveDatabus;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.room.entity.RoomVipSetBean;
import com.axend.aerosense.room.listener.OnBackCallback;
import com.axend.aerosense.room.listener.OnSwitchChageListener;
import com.axend.aerosense.room.viewmodel.RoomVipFunViewModel;
import com.blankj.utilcode.util.LogUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.axend.aerosense.base.activity.MvvmBaseActivity;
import com.axend.aerosense.common.bean.VipFunSetBean;
import com.axend.aerosense.common.ui.CustomSettingItemView;
import com.axend.aerosense.common.ui.CustomTipsDialog;
import com.axend.aerosense.common.util.FragmentUtil;
import com.axend.aerosense.room.BR;
import com.axend.aerosense.room.R;
import com.axend.aerosense.room.databinding.RoomActivityVipFunBinding;
import com.axend.aerosense.room.entity.VipFunAboutBean;
import com.axend.aerosense.room.ui.fragment.RoomSettingFragment;
import com.axend.aerosense.room.ui.fragment.vipfun.RoomBathroomUseAnalysisFragment;
import com.axend.aerosense.room.ui.fragment.vipfun.RoomNightNoBackFragment;
import com.axend.aerosense.room.ui.fragment.vipfun.RoomNightUpAnalysisFragment;
import com.axend.aerosense.room.ui.fragment.vipfun.RoomOutNoBackFragment;
import com.axend.aerosense.room.ui.fragment.vipfun.RoomSedentaryAnalysisFragment;
import com.axend.aerosense.room.ui.fragment.vipfun.RoomSleepQualityAnalysisFragment;
import com.axend.aerosense.room.ui.fragment.vipfun.RoomSleepTimeoutFragment;
import com.axend.aerosense.room.ui.fragment.vipfun.RoomStandingStillFragment;
import com.axend.aerosense.room.ui.fragment.vipfun.RoomToiletDetentionFragment;
import com.axend.aerosense.room.ui.fragment.vipfun.RoomWorkRestFragment;

/**
 * Author: ChenHongWei
 * Date: 2021/3/22 16:56
 */
public class RoomVipFunActivity extends MvvmBaseActivity<RoomActivityVipFunBinding, RoomVipFunViewModel> {

    public static final String FLAG = "ROOM_VIP_FUN_ACTIVITY";
    public static final String FLAG_SETTINGS_DATA = "FLAG_SETTINGS_DATA";
    public static final String FLAG_ACCUMULATE_SIT = "FLAG_ACCUMULATE_SIT";

    public static final int FLAG_MOTIONLESS_ALERT = 0;  //原地静止
    public static final int FLAG_TOILET_DETENTION = 1;  //卫浴滞留
    public static final int FLAG_MEAL_ANALYSIS = 2;  //未用餐提醒
    public static final int FLAG_NIGHT_NO_BACK = 3;  //起夜未归
    public static final int FLAG_REGULAR_LIFESTYLE = 4;  //熬夜提醒（原作息异常）
    public static final int FLAG_NIGHT_UP_ANALYSIS = 5;  //频繁起夜
    public static final int FLAG_SLEEP_QUALITY_ANALYSIS = 6;
    public static final int FLAG_OUT_NO_BACK = 7;  //外出未归
    public static final int FLAG_BATHROOM_USE_ANALYSIS = 8;  //频繁如厕
    public static final int FLAG_SLEEP_TIMEOUT = 9;  //卧床不起
    public static final int FLAG_SEDENTARY_ANALYSIS = 10;  //久坐提醒
    public static final int FLAG_TREND_ANALYSIS = 11;  //行动能力分析

    public static final int FLAG_NO_VITAL_SIGNALS = 12;  //心跳/呼吸骤停告警
    public static final int FLAG_BED_EXIT_WARNING = 13;  //离床告警
    public static final int FLAG_ABNORMAL_SLEEP = 14;  //作息异常

    private OnSwitchChageListener onSwitchChageListener;
    private OnBackCallback onBackCallback;
    private CustomTipsDialog tipsDialog;
    private int flag;
    private VipFunAboutBean vipFunAboutBean;
    private boolean isChange = false;  //设置是否改变
    private Fragment customFragment;

    @Override
    protected RoomVipFunViewModel getViewModel() {
        return new ViewModelProvider(this).get(RoomVipFunViewModel.class);
    }

    @Override
    protected int getBindingVariable() {
        return BR.viewModel;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.room_activity_vip_fun;
    }

    @Override
    protected void onRetryBtnClick() {

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ImmersionBar.with(this)
                .statusBarColor(android.R.color.white)
                .fitsSystemWindows(true)
                .statusBarDarkFont(true)
                .autoDarkModeEnable(true).init();
        setSupportActionBar(viewDataBinding.roomToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);//左侧添加一个默认的返回图标
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportFragmentManager().addOnBackStackChangedListener(getListener());

        //功能开关监听
        viewDataBinding.roomFunSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (onSwitchChageListener != null){
                onSwitchChageListener.onChange(buttonView, isChecked);
            }
        });

        //加载指定Fragment
        Intent intent = getIntent();
        if (intent != null){
            flag = intent.getIntExtra(FLAG, 0);
            addFragment(flag);
        }

        viewModel.isChecked.observe(this, aBoolean -> {
            if (flag != FLAG_SEDENTARY_ANALYSIS){
                viewModel.isShowFragment.setValue(aBoolean);
            }
        });

        //关于此vip功能介绍
        viewDataBinding.roomFunAbout.setOnClickListener(v -> {
            Intent i = new Intent(this, RoomVipFunAboutActivity.class);
            i.putExtra(RoomVipFunAboutActivity.FLAG_CONTENT, vipFunAboutBean);
            startActivity(i);
        });

    }

    //传值指定加载指定Fragment
    private void addFragment(int flag){
        boolean isAddFragment = true;

        switch (flag){
            case FLAG_MOTIONLESS_ALERT:
                customFragment = RoomStandingStillFragment.getInstance();
                vipFunAboutBean = new VipFunAboutBean(R.string.room_motionless_alert, R.string.room_motionless_alert_about);
                break;
            case FLAG_TOILET_DETENTION:
                customFragment = RoomToiletDetentionFragment.getInstance();
                vipFunAboutBean = new VipFunAboutBean(R.string.room_bathroom_detention, R.string.room_bathroom_detention_about);
                break;
            case FLAG_MEAL_ANALYSIS:
                isAddFragment = false;
                setVipFunTip(getString(R.string.room_meal_analysis_tips));
                setTitle(getString(R.string.room_meal_analysis));
                viewModel.isChecked.setValue(getVipSettings().getFunctionSwitch() == 1);
                vipFunAboutBean = new VipFunAboutBean(R.string.room_meal_analysis, R.string.room_meal_analysis_about);
                break;
            case FLAG_NIGHT_NO_BACK:
                customFragment = RoomNightNoBackFragment.getInstance();
                vipFunAboutBean = new VipFunAboutBean(R.string.room_night_no_back, R.string.room_night_no_back_about);
                break;
            case FLAG_REGULAR_LIFESTYLE:
                customFragment = RoomWorkRestFragment.getInstance();
//                viewModel.isChecked.setValue(getVipSettings().getFunctionSwitch() == 1);
                vipFunAboutBean = new VipFunAboutBean(R.string.room_regular_lifestyle, R.string.room_regular_lifestyle_about);
                break;
            case FLAG_NIGHT_UP_ANALYSIS:
                customFragment = RoomNightUpAnalysisFragment.getInstance();
                vipFunAboutBean = new VipFunAboutBean(R.string.room_night_up_analysis, R.string.room_night_up_analysis_about);
                break;
            case FLAG_SLEEP_QUALITY_ANALYSIS:
                customFragment = RoomSleepQualityAnalysisFragment.getInstance();
                break;
            case FLAG_OUT_NO_BACK:
                customFragment = RoomOutNoBackFragment.getInstance();
                vipFunAboutBean = new VipFunAboutBean(R.string.room_out_no_back, R.string.room_out_no_back_about);
                break;
            case FLAG_BATHROOM_USE_ANALYSIS:
                customFragment = RoomBathroomUseAnalysisFragment.getInstance();
                vipFunAboutBean = new VipFunAboutBean(R.string.room_bathroom_use_analysis, R.string.room_bathroom_use_analysis_about);
                break;
            case FLAG_SLEEP_TIMEOUT:
                customFragment = RoomSleepTimeoutFragment.getInstance();
                vipFunAboutBean = new VipFunAboutBean(R.string.room_sleep_timeout, R.string.room_sleep_timeout_about);
                break;
            case FLAG_SEDENTARY_ANALYSIS:
                customFragment = RoomSedentaryAnalysisFragment.getInstance();
                vipFunAboutBean = new VipFunAboutBean(R.string.room_sedentary_analysis, R.string.room_sedentary_analysis_about);
                break;
            case FLAG_TREND_ANALYSIS:
                isAddFragment = false;
                setVipFunTip(getString(R.string.room_trend_analysis_tips));
                setTitle(getString(R.string.room_trend_analysis));
                viewModel.isChecked.setValue(getVipSettings().getFunctionSwitch() == 1);
                vipFunAboutBean = new VipFunAboutBean(R.string.room_trend_analysis, R.string.room_trend_analysis_about);
                break;
            case FLAG_NO_VITAL_SIGNALS:
                // 心跳/呼吸骤停告警
                isAddFragment = false;
                setVipFunTip(R.string.room_no_vital_signals_tips);
                setTitle(getString(R.string.room_no_vital_signals));
                viewModel.isChecked.setValue(getVipSettings().getFunctionSwitch() == 1);
                vipFunAboutBean = new VipFunAboutBean(R.string.room_no_vital_signals, R.string.room_no_vital_signals_about);
                break;
            case FLAG_BED_EXIT_WARNING:
                // 离床告警
                isAddFragment = false;
                setVipFunTip(R.string.room_bed_exit_warning_tips);
                setTitle(getString(R.string.room_bed_exit_warning));
                viewModel.isChecked.setValue(getVipSettings().getFunctionSwitch() == 1);
                vipFunAboutBean = new VipFunAboutBean(R.string.room_bed_exit_warning, R.string.room_bed_exit_warning_about);
                break;
            case FLAG_ABNORMAL_SLEEP:
                //作息异常
                isAddFragment = false;
                setVipFunTip(R.string.room_abnormal_sleep_tips);
                setTitle(getString(R.string.room_abnormal_sleep));
                viewModel.isChecked.setValue(getVipSettings().getFunctionSwitch() == 1);
                vipFunAboutBean = new VipFunAboutBean(R.string.room_abnormal_sleep, R.string.room_abnormal_sleep_about);
                break;
        }

        if (isAddFragment && customFragment != null){
            FragmentUtil.add(this, viewDataBinding.roomContent.getId(), customFragment, null, false);
        }
    }

    /*public void isChangeData(){
        ViewGroup viewGroup = (ViewGroup) customFragment.getView();
        for (int i = 0; i < viewGroup.getChildCount(); i++){
            View child = viewGroup.getChildAt(i);
            if (!(child instanceof CustomSettingItemView)){
                child.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        LogUtils.d(this, event.getAction());
                        setChange(true);
                        return false;
                    }
                });
            }
        }
    }*/

    private void showSaveSettingDialog(){
        if (isChange()){
            LogUtils.d("保存设置");
            saveSettings();
            LiveDatabus.getInstance().with(Gobal.EVENT_KEY.REFESH_ROOM, Integer.class).postValue(1);
//            setResult(RoomSettingFragment.REQUEST_VIP_SET_CODE, getIntent());
//            tipsDialog = new CustomTipsDialog(this, getString(R.string.room_is_save_setting));
//            tipsDialog.setOnClickBottomListener(new CustomTipsDialog.OnClickBottomListener() {
//                @Override
//                public void onPositiveClick() {
//                    tipsDialog.dismiss();
//                    LogUtils.d("保存设置");
//                    saveSettings();
//                    setResult(RoomSettingFragment.REQUEST_VIP_SET_CODE, getIntent());
//                }
//
//                @Override
//                public void onNegtiveClick() {
//                    tipsDialog.dismiss();
//                    LogUtils.d("不保存设置");
//                    onBackPressed();
//                }
//            });
//            tipsDialog.show();
        }else {
            onBackPressed();
        }
    }

    // 保存只有开关设置vip功能
    private void saveSettings(){
        RoomVipSetBean vipSettings = getVipSettings();
        VipFunSetBean bean = new VipFunSetBean(vipSettings.getRoomUuid(), vipSettings.getRoomType(), getSwitchState());
        String url = null;
        switch (flag){
            case FLAG_MEAL_ANALYSIS:
                url = UrlApi.URL.SetHaveMeals.getUrl();
                break;
            case FLAG_REGULAR_LIFESTYLE:
                url = UrlApi.URL.SetWorkAndrest.getUrl();
                break;
            case FLAG_TREND_ANALYSIS:
                url = UrlApi.URL.SetTrendAnalysis.getUrl();
                break;
            case FLAG_NO_VITAL_SIGNALS:
                url = UrlApi.URL.SetNoVitalSignals.getUrl();
                break;
            case FLAG_BED_EXIT_WARNING:
                url = UrlApi.URL.SetBedExitWarning.getUrl();
                break;
            case FLAG_ABNORMAL_SLEEP:
                url = UrlApi.URL.SetAbnormalSleep.getUrl();
                break;
        }

        if (null == url) return;
        viewModel.saveSettings(this, bean, url);
    }

    /** 获取设置Bean */
    private RoomVipSetBean getVipSettings(){
        return (RoomVipSetBean) getIntent().getSerializableExtra(RoomVipFunActivity.FLAG_SETTINGS_DATA);
    }

    private FragmentManager.OnBackStackChangedListener getListener() {
        FragmentManager.OnBackStackChangedListener result = new FragmentManager.OnBackStackChangedListener() {
            public void onBackStackChanged() {
                FragmentManager manager = getSupportFragmentManager();
                if (manager != null) {
                    Fragment currFrag = (Fragment) manager.findFragmentById(getContentId());
                    currFrag.onResume();
                }
            }
        };

        return result;
    }

    public int getContentId() {
        return viewDataBinding.roomContent.getId();
    }

    public void setTitle(String title) {
        viewDataBinding.roomTitle.setText(title);
    }

    /** 设置VIP功能提示 */
    public void setVipFunTip(String text){
        viewDataBinding.roomVipFunTip.setText(text);
    }
    public void setVipFunTip(int id){
        viewDataBinding.roomVipFunTip.setText(id);
    }

    /** 设置开关左边文字 */
    public void setLeftText(String text){
        viewDataBinding.roomFunSwitch.setLeftText(text);
    }

    /** 设置开关状态 */
    public void setSwitchChange(boolean b){
        viewModel.isChecked.setValue(b);
    }

    /** 获取开关状态 */
    public int getSwitchState(){
        return viewModel.isChecked.getValue() ? 1 : 0;
    }

    public boolean isChange() {
        if (!isChange){
            if (viewDataBinding.roomFunSwitch.isChange()){
                isChange = true;
            }
            if (customFragment != null && !isChange){
                ViewGroup viewGroup = (ViewGroup) customFragment.getView();
                if (viewGroup.getChildCount() > 0){
                    for (int i = 0; i < viewGroup.getChildCount(); i++){
                        View view = viewGroup.getChildAt(i);
                        if (view instanceof CustomSettingItemView){
                            CustomSettingItemView customSettingItemView = (CustomSettingItemView) view;
                            if (customSettingItemView.isChange()){
                                isChange = true;
                                break;
                            }
                        }
                    }
                }
            }
        }
        return isChange;
    }

    public void setChange(boolean change) {
        isChange = change;
    }

    public void setSwitchChageListener(OnSwitchChageListener listener){
        this.onSwitchChageListener = listener;
    }

    public void setOnBackCallback(OnBackCallback onBackCallback){
        this.onBackCallback = onBackCallback;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if (onBackCallback != null){
                //在Fragment时
                onBackCallback.onBack();
            }else if (flag == FLAG_MEAL_ANALYSIS
                    || flag == FLAG_REGULAR_LIFESTYLE
                    || flag == FLAG_TREND_ANALYSIS
                    || flag == FLAG_NO_VITAL_SIGNALS
                    || flag == FLAG_BED_EXIT_WARNING
                    || flag == FLAG_ABNORMAL_SLEEP){
                //在Activity时
                showSaveSettingDialog();
            } else {
                onBackPressed();
            }
        }
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            if (onBackCallback != null){
                //在Fragment时
                return onBackCallback.onBack();
            }else if (flag == FLAG_MEAL_ANALYSIS
                    || flag == FLAG_REGULAR_LIFESTYLE
                    || flag == FLAG_TREND_ANALYSIS
                    || flag == FLAG_NO_VITAL_SIGNALS
                    || flag == FLAG_BED_EXIT_WARNING
                    || flag == FLAG_ABNORMAL_SLEEP){
                //在Activity时
                showSaveSettingDialog();
            } else {
                onBackPressed();
                return true;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
            finish();
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (tipsDialog != null){
            tipsDialog.dismiss();
        }
        onSwitchChageListener = null;
        onBackCallback = null;
    }
}
